package com.emellend.api11.preference;
import com.emellend.api11.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

public class MyPreference extends Preference {
	private int clickCounter;

	public MyPreference(Context context, AttributeSet attrs) {
		super(context,attrs);
		setWidgetLayoutResource(R.layout.preference_widget_mypreference);
	}
	
	@Override
	protected void onBindView(View view) {
		super.onBindView(view);
		final TextView textView=(TextView) view.findViewById(R.id.mypreference_widget);
		if (textView!=null) {
			textView.setText(String.valueOf(clickCounter));
		}
	}
	
	@Override
	protected void onClick() {
		super.onClick();
		int newValue=clickCounter+1;
		if (!callChangeListener(newValue)) {
			return;
		}
		clickCounter=newValue;
		persistInt(clickCounter);
		notifyChanged();
	}
	
	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		return a.getInteger(index, 0);
	}
	
	@Override
	protected void onSetInitialValue(boolean restorePersistedValue,
			Object defaultValue) {
		if (restorePersistedValue) {
			clickCounter=getPersistedInt(clickCounter);
		}else {
			int value=(Integer) defaultValue;
			clickCounter=value;
			persistInt(clickCounter);
		}
	}
	
	@Override
	protected Parcelable onSaveInstanceState() {
		final Parcelable parcelable=super.onSaveInstanceState();
		if (isPersistent()) {
			return parcelable;
		}
		final SavedState savedState=new SavedState(parcelable);
		savedState.clickCounter=clickCounter;
		return savedState;
	}
	
	@Override
	protected void onRestoreInstanceState(Parcelable state) {
		if (!state.getClass().equals(SavedState.class)) {
			super.onRestoreInstanceState(state);
			return;
		}
		SavedState myState=(SavedState) state;
		super.onRestoreInstanceState(myState.getSuperState());
		clickCounter=myState.clickCounter;
		notifyChanged();
	}

	private static class SavedState extends BaseSavedState{
		int clickCounter;
		
		public SavedState(Parcel parcel) {
			super(parcel);
			clickCounter=parcel.readInt();
		}
		
		public SavedState(Parcelable superState){
			super(superState);
		}
		
		@Override
		public void writeToParcel(Parcel dest, int flags) {
			super.writeToParcel(dest, flags);
			dest.writeInt(clickCounter);
		}
		
		public static final Parcelable.Creator<SavedState> CREATOR= new Parcelable.Creator<SavedState>() {
			
			public SavedState[] newArray(int size) {
				return new SavedState[size];
			}
			public SavedState createFromParcel(Parcel source) {
				return new SavedState(source);
			}
		};
		
	}
}
